import axios from '../axios';

var depot = {

};

depot.get = function ({ url, config = {}, cb, ce }) {
    axios.get(url, config).then((res) => {
        if (res.status === 200) {
            let result = res.data;
            cb(result);
        }
    }).catch((error) => {
        if (ce) {
            ce(error);
        }
        console.error('请求错误：', error);
    });
};

// depot.get({
//     url: '',
//     config: {
//         params: {
//             id: this.id,
//             code: this.code
//         }
//     },
//     cb: (data) => {
//         console.log(data.code === 0)
//     }
// })

depot.post = function ({ url, data, cb, ce }) {
    // let _data = qs.stringify(data)
    axios.post(url, data).then(
        (res) => {
            if (res.status === 200) {
                if (res.status === 200) {
                    let result = res.data;
                    cb(result);
                }
            }
        }).catch((error) => {
        if (ce) {
            ce(error);
        }
        console.log(error);
    });
};

/**
 * 设置缓存
 * @param key
 * @param value
 */
depot.setStorage = function (key, value) {
    if (arguments.length === 2) {
        let v = value;
        if (typeof v === 'object') {
            v = JSON.stringify(v);
            v = 'obj-' + v;
        } else {
            v = 'str-' + v;
        }
        localStorage.setItem(key, v);
    }
};
/**
 * 根据key取得缓存
 * @param key
 */
depot.getStorage = function (key) {
    let v = localStorage.getItem(key);
    if (!v) {
        return;
    }
    if (v.indexOf('obj-') === 0) {
        v = v.slice(4);
        return JSON.parse(v);
    } else if (v.indexOf('str-') === 0) {
        return v.slice(4);
    }
};
/**
 * 根据key删除缓存
 * @param key
 */
depot.rmStorage = function (key) {
    localStorage.removeItem(key);
};
/**
 * 清空缓存
 */
depot.clearStorage = function () {
    localStorage.clear();
};

/**
 * 解析page
 * @param {*} page
 */
depot.analysisPage = function (page) {
    return page <= 0 ? 0 : page - 1;
};

export default () => {
    window.depot = depot;
};
